/*
Designer   : Renyangang

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fpga

import (
	"fmt"
	"fpga-vboard/pins"
)

type ICDynLibV1 interface {
	Eval(inputSig []byte, outputSig []byte)
	Init()
	Stop()
	Close()
}

type FpgaPlugin struct {
	Name          string
	DynLibPath    string
	InputPins     []*pins.SignalPin
	OutputPins    []*pins.SignalPin
	InputPinData  []byte
	OutputPinData []byte
	dynLib        *DynLibEval
}

func NewFpgaPlugin(name string, dynLibPath string, inputSignals []*pins.SignalPin, outputSignals []*pins.SignalPin) *FpgaPlugin {
	return &FpgaPlugin{
		Name:       name,
		DynLibPath: dynLibPath,
		InputPins:  inputSignals,
		OutputPins: outputSignals,
	}
}

func (p *FpgaPlugin) Init() error {
	dynLib, err := NewDynLibEval(p.DynLibPath)
	if err != nil {
		return err
	}
	p.dynLib = dynLib
	byteSize := uint(0)
	for _, inputSig := range p.InputPins {
		byteSize += ((inputSig.BitSize + 7) / 8)
	}
	p.InputPinData = make([]byte, byteSize)
	pos := 0
	for _, inputSig := range p.InputPins {
		inputSig.Value.SetBytesValue(p.InputPinData[pos : pos+int((inputSig.BitSize+7)/8)])
		pos += int((inputSig.BitSize + 7) / 8)
	}
	byteSize = 0
	for _, outputSig := range p.OutputPins {
		byteSize += ((outputSig.BitSize + 7) / 8)
	}
	p.OutputPinData = make([]byte, byteSize)
	pos = 0
	for _, outputSig := range p.OutputPins {
		// fmt.Println("outputSig", outputSig.Name, pos)
		outputSig.Value.SetBytesValue(p.OutputPinData[pos : pos+int((outputSig.BitSize+7)/8)])
		pos += int((outputSig.BitSize + 7) / 8)
	}
	p.dynLib.Init()
	return nil
}

func (p *FpgaPlugin) Stop() {
	if p.dynLib != nil {
		p.dynLib.Stop()
	}
}

func (p *FpgaPlugin) Uninit() {
	if p.dynLib != nil {
		p.dynLib.Close()
	}
}

func (p *FpgaPlugin) makeInputPins() {
	pins.MappingPinBitValues()
	// pos := 0
	// for _, inputSig := range p.InputPins {
	// 	for i := uint(0); i < ((inputSig.BitSize + 7) / 8); i++ {
	// 		p.InputPinData[pos] = inputSig.Value.GetByteValue(i)
	// 		pos++
	// 	}
	// }
}

func (p *FpgaPlugin) makeOutputPins() {
	// pos := 0
	// for _, outputSig := range p.OutputPins {
	// 	for i := uint(0); i < ((outputSig.BitSize + 7) / 8); i++ {
	// 		outputSig.Value.SetByteValue(i, p.OutputPinData[pos])
	// 		pos++
	// 	}
	// }
	pins.MappingPinBitValues()
}

func (p *FpgaPlugin) Eval() error {
	if p.dynLib == nil {
		return fmt.Errorf("plugin %s is not initialized", p.Name)
	}
	p.makeInputPins()
	p.dynLib.Eval(p.InputPinData, p.OutputPinData)
	p.makeOutputPins()
	return nil
}
